﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UIFlowManager : Singleton<UIFlowManager> 
{
	protected UIFlowManager () {}

	public GenericGame m_GenericGame;
	public GameObject m_PopupScreen;
	public GameObject m_TurnsLeft;
	public GameObject m_PlayerTurnText;

	private int m_CurrentGameCurrentTurn;

	private bool m_UIFlowReady;
	public bool UIFlowReady
	{
		get { return m_UIFlowReady; }
		set { m_UIFlowReady = value; }
	}

	private void Start () 
	{
	}

	private void Update () 
	{

	}

	public void StartPlayerTurnAnim()
	{
		m_UIFlowReady = false;
		m_CurrentGameCurrentTurn = (int)m_GenericGame.GetType().GetProperty("CurrentTurn").GetValue(m_GenericGame, null);
		
		m_PlayerTurnText.GetComponent<TextMesh>().text = "P" + (m_CurrentGameCurrentTurn + 1).ToString() + "'s Turn";
		m_PlayerTurnText.transform.GetChildByName("GenericRectangle").GetComponent<SpriteRenderer>().material.color = GamesManager.Instance.m_PlayersColor[m_CurrentGameCurrentTurn];
		m_PlayerTurnText.GetComponent<Animator>().SetTrigger("OnNewTurn");
	}

	public void AddResultScreen(List<int> i_Winners, List<GameObject> i_WinnersIcon = null)
	{
		GameObject popup = (GameObject)Instantiate(m_PopupScreen);
		string winnersText = "";
		for(int i = 0; i < i_Winners.Count; i++)
		{
			if(i_WinnersIcon != null)
			{
				GameObject icon = (GameObject)Instantiate(i_WinnersIcon[i]);

				SpriteRenderer iconRenderer = icon.GetComponent<SpriteRenderer>();
				iconRenderer.sortingLayerName = "HUD";
				iconRenderer.sortingOrder = 5;

				Color newAlpha = iconRenderer.color;
				newAlpha.a = 1f;
				iconRenderer.color = newAlpha;
				
				icon.transform.localScale = Vector3.one;

				float posX = icon.transform.localScale.x * i - ((i_Winners.Count - 1)/2.0f);
				icon.transform.position = new Vector3(posX, 2.25f, -4.1f);
				icon.transform.parent = popup.transform;
			}

			if(i == 0)
			{
				winnersText += ("P" + (i_Winners[i]).ToString());
			}
			else
			{
				winnersText += (", P" + (i_Winners[i]).ToString());
			}
		}
		
		popup.transform.position = new Vector3(0f, 0f, -4f);
		popup.transform.GetChildByName("WinnersText").GetComponent<TextMesh>().text = winnersText;
		if(i_Winners.Count == 1)
		{
			popup.transform.GetChildByName("WinText").GetComponent<TextMesh>().text = "WINS!!!";
		}
		else
		{
			popup.transform.GetChildByName("WinText").GetComponent<TextMesh>().text = "WIN!!!";
		}
	}

	public void SetTurnLeftText(string i_TurnLeft)
	{
		m_TurnsLeft.transform.GetChildByName("ValueText").GetComponent<TextMesh>().text = i_TurnLeft;
	}

	public void OffsetPlayerTurnText(float x, float y)
	{
		Vector3 newPos = m_PlayerTurnText.transform.position;
		newPos.x = x;
		newPos.y = y;

		m_PlayerTurnText.transform.position = newPos;
	}

	public void EnableUIFlow()
	{
		m_UIFlowReady = true;
	}
	
	public void DisableUIFlow()
	{
		m_UIFlowReady = false;
	}
}
